﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YiSha.Service.OrganizationManage;
using YiSha.Data.Repository;
using YiSha.Entity.OrganizationManage;
using YiSha.Enums;
using YiSha.Model;
using YiSha.Model.Param.OrganizationManage;
using YiSha.Model.Result;
using YiSha.Util;
using YiSha.Util.Model;

namespace YiSha.Service.OrganizationManage
{
    public class DepartmentService : RepositoryFactory
    {
        public UserService UserService { get; set; }
        #region 获取数据
        public async Task<TData<List<DepartmentEntity>>> GetList(DepartmentListParam param)
        {
            TData<List<DepartmentEntity>> obj = new TData<List<DepartmentEntity>>();
            obj.Data = this.SqlSugarAdapters.GetList<DepartmentEntity>(s => s.Valid);

            obj.MsgCode = MsgCode.Success;
            return obj;
        }

        public async Task<TData<List<ZtreeInfo>>> GetZtreeDepartmentList(DepartmentListParam param)
        {
            var obj = new TData<List<ZtreeInfo>>();
            obj.Data = new List<ZtreeInfo>();
            //查询顶级部门信息
            var departmentList = this.SqlSugarAdapters.GetList<DepartmentEntity>(s => s.Valid);
            foreach (DepartmentEntity department in departmentList)
            {
                obj.Data.Add(new ZtreeInfo
                {
                    id = department.Id,
                    pId = department.ParentId,
                    name = department.DepartmentName
                });
            }
            obj.MsgCode = MsgCode.Success;
            return obj;
        }

        public async Task<TData<List<ZtreeInfo>>> GetZtreeUserList(DepartmentListParam param)
        {
            var obj = new TData<List<ZtreeInfo>>();
            obj.Data = new List<ZtreeInfo>();
            List<DepartmentEntity> departmentList = this.SqlSugarAdapters.GetList<DepartmentEntity>(s => s.Valid);
            //OperatorInfo operatorInfo = await Operator.Instance.Current();
            //if (operatorInfo.IsSystem != 1)
            //{
            //    List<long> childrenDepartmentIdList = await GetChildrenDepartmentIdList(departmentList, operatorInfo.DepartmentId.Value);
            //    departmentList = departmentList.Where(p => childrenDepartmentIdList.Contains(p.Id.Value)).ToList();
            //}
            List<UserEntity> userList = UserService.GetList(null).Result.Data;
            foreach (DepartmentEntity department in departmentList)
            {
                obj.Data.Add(new ZtreeInfo
                {
                    id = department.Id,
                    pId = department.ParentId,
                    name = department.DepartmentName
                });
                var userIdList = userList.Where(t => t.DepartmentId == department.Id).Select(t => t.Id).ToList();
                foreach (UserEntity user in userList.Where(t => userIdList.Contains(t.Id)))
                {
                    obj.Data.Add(new ZtreeInfo
                    {
                        id = user.Id,
                        pId = department.Id,
                        name = user.RealName
                    });
                }
            }
            obj.MsgCode = MsgCode.Success;
            return obj;
        }

        public async Task<TData<DepartmentEntity>> GetEntity(string id)
        {
            TData<DepartmentEntity> obj = new TData<DepartmentEntity>();
            obj.Data = this.SqlSugarAdapters.GetEntity<DepartmentEntity>(s => s.Id == id && s.Valid);
            obj.MsgCode = MsgCode.Success;
            return obj;
        }

        #endregion

        #region 提交数据
        /// <summary>
        /// 新增/修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public Task<TData<string>> SaveForm(DepartmentEntity entity)
        {
            TData<string> obj = new TData<string>();
            try
            {
                if (!entity.Id.IsEmpty() && entity.Id == entity.ParentId)
                {
                    obj.MsgCode = MsgCode.Fail;
                    obj.Msg = "不能选择自己作为上级部门！";
                    return Task.FromResult(obj);
                }
                var tempArr = entity.ParentId.Split(",");
                entity.ParentId = tempArr.Length > 1 ? tempArr[tempArr.Length - 1] : entity.ParentId;
                var department = this.SqlSugarAdapters.GetEntity<DepartmentEntity>(s => s.DepartmentName == entity.DepartmentName && s.Valid);
                if (!department.IsEmpty())
                {
                    obj.MsgCode = MsgCode.Fail;
                    obj.Msg = "部门名称已经存在！";
                    return Task.FromResult(obj);
                }
                if (entity.Id.IsEmpty())
                {
                    _ = entity.Create();
                    this.SqlSugarAdapters.Insert(entity);
                }
                else
                {
                    _ = entity.Modify();
                    this.SqlSugarAdapters.Update(entity);
                }
                obj.Msg = "操作成功";
                return Task.FromResult(obj);
            }
            catch (Exception ex)
            {
                obj.Msg = ex.Message;
                obj.MsgCode = MsgCode.Fail;
                return Task.FromResult(obj);
            }
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<TData> DeleteForm(List<string> ids)
        {
            TData obj = new TData();
            var departmentList = this.SqlSugarAdapters.GetList<DepartmentEntity>(s => s.Valid);
            if (departmentList.Count > 0)
                foreach (var id in ids)
                {
                    var department = departmentList.Where(s => s.ParentId == id).FirstOrDefault();
                    if (!department.IsEmpty())
                    {
                        obj.Msg = "该部门下面有子部门！";
                        return obj;
                    }
                }
            // await departmentService.DeleteForm(ids);
            this.SqlSugarAdapters.Delete<DepartmentEntity>(s => ids.Contains(s.Id));
            obj.MsgCode = MsgCode.Success;
            return obj;
        }
        #endregion

        #region 公共方法
        /// <summary>
        /// 获取当前部门及下面所有的部门
        /// </summary>
        /// <param name="departmentList"></param>
        /// <param name="departmentId"></param>
        /// <returns></returns>
        public async Task<List<string>> GetChildrenDepartmentIdList(List<DepartmentEntity> departmentList, string departmentId)
        {
            if (departmentList == null)
            {
                departmentList = this.SqlSugarAdapters.GetList<DepartmentEntity>(s => s.Valid);
            }
            var departmentIdList = new List<string>();
            departmentIdList.Add(departmentId);
            GetChildrenDepartmentIdList(departmentList, departmentId, departmentIdList);
            return departmentIdList;
        }
        #endregion 

        #region 私有方法
        /// <summary>
        /// 获取该部门下面所有的子部门
        /// </summary>
        /// <param name="departmentList"></param>
        /// <param name="departmentId"></param>
        /// <param name="departmentIdList"></param>
        private void GetChildrenDepartmentIdList(List<DepartmentEntity> departmentList, string departmentId, List<string> departmentIdList)
        {
            var children = departmentList.Where(p => p.ParentId == departmentId).Select(p => p.Id).ToList();
            if (children.Count > 0)
            {
                departmentIdList.AddRange(children);
                foreach (var id in children)
                {
                    GetChildrenDepartmentIdList(departmentList, id, departmentIdList);
                }
            }
        }
        #endregion
    }
}
